﻿using CrayonAPI.Core;
using CrayonAPI.Web.Core.Startups;
using HongHui_WX.Web.Core.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System.Text.Encodings.Web;

namespace CrayonAPI.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSqlsugar();
            services.AddConsoleFormatter();
            services.AddJwt<JwtHandler>();

            services.AddCorsAccessor();

            services.AddControllers()
                    .AddInjectWithUnifyResult();

            services.AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
            });
            services.AddLogStartUp();
            //添加远程请求服务
            services.AddRemoteRequest(options =>
            {
                // 忽略所有HTTP请求证书校验
                options.ApproveAllCerts();
            });
            //保存返回值命名风格(默认会序列化为小驼峰)
            services.AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
            //使用EventBus服务
            services.AddEventBus();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //开发环境返回异常页面
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCorsAccessor();
            //为第三方请求颁发token
            //app.UseMiddleware<TrustRequestMiddleware>();

            //鉴权授权
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            //黑名单
            //app.UseMiddleware<BlackListMiddleware>();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
